package com.mcxx.handler;

import cn.hutool.core.lang.ClassScanner;
import com.google.common.collect.Maps;
import com.mcxx.aspect.annotation.BizTypeHandler;
import com.mcxx.constant.BusinessConstant;
import com.mcxx.context.BizHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class BizHandleProcessor implements BeanFactoryPostProcessor {
    private final static String HANNDLER_PACKAGE = "com.mcxx.handler";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, Class> handlerMap = Maps.newHashMapWithExpectedSize(3);
        ClassScanner.scanPackageByAnnotation(HANNDLER_PACKAGE, BizTypeHandler.class).forEach(clazz -> {
            String handleType = clazz.getAnnotation(BizTypeHandler.class).handleType();
            String userLevel = clazz.getAnnotation(BizTypeHandler.class).userLevel();
            String businessType = clazz.getAnnotation(BizTypeHandler.class).businessType();
            String areaCode = clazz.getAnnotation(BizTypeHandler.class).areaCode();
            String recheckType = clazz.getAnnotation(BizTypeHandler.class).recheckType();
            String operateStep = clazz.getAnnotation(BizTypeHandler.class).operateStep();

            StringBuffer sb = new StringBuffer();
            sb.append(StringUtils.isEmpty(handleType)? BusinessConstant.COMMON:handleType).append("&");
            sb.append(StringUtils.isEmpty(userLevel)?BusinessConstant.COMMON:userLevel).append("&");
            sb.append(StringUtils.isEmpty(areaCode)?BusinessConstant.COMMON:areaCode).append("&");
            sb.append(StringUtils.isEmpty(businessType)?BusinessConstant.COMMON:businessType).append("&");
            sb.append(StringUtils.isEmpty(recheckType)?BusinessConstant.COMMON:recheckType).append("&");
            sb.append(StringUtils.isEmpty(operateStep)?BusinessConstant.COMMON:operateStep).append("&");
            handlerMap.put(sb.toString(), clazz);
        });

        BizHandlerContext handlerContext = new BizHandlerContext(handlerMap);
        configurableListableBeanFactory.registerSingleton(BizHandlerContext.class.getName(), handlerContext);
    }
}
